import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

///本地持久化,本地缓存

class SPUtil {
  static SharedPreferences? sharedPreferences;

  //关键字
  static const userInfoKey = "USERINFO";

  //初始化
  static Future<bool> init() async{
    sharedPreferences = await SharedPreferences.getInstance();
    return true;
  }

  //保存map
  static Future<bool> saveMap(
      {required String key, required Map<String, dynamic> value}) async {
    if(sharedPreferences==null) return false;
    return await sharedPreferences!.setString(key, jsonEncode(value));
  }

  //获取map
  static Map<String, dynamic>? getMap({required String key}) {
    if (sharedPreferences == null) {
      return null;
    } else {
      String? result = sharedPreferences!.getString(key);
      if (result != null) {
        return jsonDecode(result);
      } else {
        return null;
      }
    }
  }

  //删除
  static deleteData({required String key}) async {
    sharedPreferences ??= await SharedPreferences.getInstance();
    sharedPreferences!.remove(key);
  }

  //清空缓存
  static clearCash() async {
    sharedPreferences ??= await SharedPreferences.getInstance();
    sharedPreferences!.clear();
  }
}
